//
//  HomeViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/4/1.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "HomeViewController.h"
#import "ButWhatMapView.h"
#import "SearchViewController.h"
#import "RootMallView.h"
#import "RootLaundryView.h"
#import "NearTheShopViewController.h"
#import "RootMessageViewController.h"
#import "MakeAnAppointmentToDoLaundryViewController.h"
#import "MemberPrepaidPhoneViewController.h"
#import "ContactCustomerServiceViewController.h"
#import "IWantToTakeTheClothesViewController.h"
#import "MallShopSecondViewController.h"

#import "ScanViewController.h"

@interface HomeViewController ()

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *headView;
@property (nonatomic,strong) NSArray *bannerArray;
@property (nonatomic,strong) NSMutableArray *dataArray;
Strong SDCycleScrollView *sdcView;
Strong UILabel *titleLabel;
Strong RootMallView *rootMallView;
Strong RootLaundryView *rootLaundryView;
Strong UIPageControl *pageControl;
Strong UILabel *messageLabel;
- (void)messageButton;

@end

//网络
@implementation HomeViewController (NetWorking)

- (void)viewCommodityInformation{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"longitude":[UserModel sharedInstanced].longitude,
                                 @"latitude":[UserModel sharedInstanced].latitude};
    [[AFAppDotNetAPIClient sharedClient] POST:@"wardrobe/Mobile_Phone_Terminal/viewCommodityInformation.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            MakeAnAppointmentToDoLaundryViewController *vc = [MakeAnAppointmentToDoLaundryViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            vc.aId = responseObject[@"obj"][0][@"a_id"];
            vc.eId = responseObject[@"obj1"];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

/**
 查看消息未读数量
 */
- (void)viewSystemMessages{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auId":[UserModel sharedInstanced].userId,
                                 @"type":@"1",
                                 @"category":@"1",
                                 @"read_state":@"1"};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/User_Message/viewSystemMessages.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.dataArray removeAllObjects];
        UIButton *messageButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
        [messageButton setImage:[UIImage imageNamed:@"root_message"] forState:UIControlStateNormal];
        [messageButton addTarget:self action:@selector(messageButton) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem * shieldButtonBarButton = [[UIBarButtonItem alloc] initWithCustomView:messageButton];
        self.navigationItem.rightBarButtonItems = @[shieldButtonBarButton];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            self.messageLabel.text = [NSString stringWithFormat:@"%@",responseObject[@"obj1"]];
            [messageButton addSubview:self.messageLabel];
        }
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        UIButton *messageButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
        [messageButton setImage:[UIImage imageNamed:@"root_message"] forState:UIControlStateNormal];
        [messageButton addTarget:self action:@selector(messageButton) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem * shieldButtonBarButton = [[UIBarButtonItem alloc] initWithCustomView:messageButton];
        self.navigationItem.rightBarButtonItems = @[shieldButtonBarButton];
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

- (void)getBanner{
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] GET:@"/LaundryMall/Advertisement/getSystemData.action" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            NSString *str = [[NSURL URLOffsetIPWithString:responseObject[@"obj"][@"indexAdver"]]absoluteString];
            self.sdcView.imageURLStringsGroup = @[str];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self showError:error];
        [self hiddenProgressHUD];
    }];
    /*
     //原来的接口
    NSDictionary *parameters = @{@"levels":@"1"};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Advertisement/displayAd.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            NSString *str = [[NSURL URLOffsetIPWithString:responseObject[@"obj"][@"picture_path"]]absoluteString];
            self.sdcView.imageURLStringsGroup = @[str];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self showError:error];
    }];
     */
}

- (void)getMallData{
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Header_Management/showLevelHeadingsAPP.action" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            self.rootMallView.dataArray = responseObject[@"obj"];
            self.pageControl.numberOfPages =  self.rootMallView.dataArray.count / 6 + (self.rootMallView.dataArray.count % 6 == 0 ? 0 : 1);
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self showError:error];
    }];
}

//获取洗衣列表接口
- (void)getUnreciveOrderInfo{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"page":@"0",
                                 @"pageSize":@"1",
                                 @"uId":[UserModel sharedInstanced].userId
                                 };
    [[AFAppDotNetAPIClient sharedClient] POST:@"wardrobe/Laundry_Order/getUnreciveOrderInfo.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            if ([responseObject[@"data"] count] > 0) {
                self.titleLabel.text = [NSString stringWithFormat:@"您有一个快递包裹至%@,取件码【%@】,请您尽快取件！",responseObject[@"data"][0][@"address"],responseObject[@"data"][0][@"pickup_password"]];
            }else{
                self.titleLabel.text = @"您还没有取件消息！";
            }
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

@end

//UI
@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getBanner];
    [self getMallData];
    [self getUnreciveOrderInfo];
    [[ButWhatMapView sharedInstanced]startUpdatingLocation:^{
        
    }];
    [self.view addSubview:self.tableView];
    
    self.navigationItem.title = @"欢迎使用洗衣柜APP";
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"root_address"] style:0 target:self action:@selector(addressClick)];
//    badgeValue
    UIButton * locationBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30/WIDTH_5S_SCALE, 30/WIDTH_5S_SCALE)];
    [locationBtn setImage:[UIImage imageNamed:@"root_address"] forState:UIControlStateNormal];
    [locationBtn addTarget:self action:@selector(addressClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * locationItem = [[UIBarButtonItem alloc] initWithCustomView:locationBtn];
    UIButton * scanBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30/WIDTH_5S_SCALE, 30/WIDTH_5S_SCALE)];
    [scanBtn setImage:[UIImage imageNamed:@"saoyisao"] forState:UIControlStateNormal];
    [scanBtn addTarget:self action:@selector(scanBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * scanItem = [[UIBarButtonItem alloc] initWithCustomView:scanBtn];
    self.navigationItem.leftBarButtonItems = @[locationItem, scanItem];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewDidAppear:animated];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nTestViewDidClickBtn) name:@"预约洗衣" object:nil];
    [self viewSystemMessages];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Event

- (void)nTestViewDidClickBtn{
    [self viewCommodityInformation];
}

- (void)messageButton{
    RootMessageViewController *vc = [RootMessageViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)addressClick{
    NearTheShopViewController *vc = [NearTheShopViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scanBtnClick:(UIButton *)sender{
    NSLog(@"扫一扫");
    
    ScanViewController * vc = [[ScanViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)titleLabelCkick{
    IWantToTakeTheClothesViewController *vc = [IWantToTakeTheClothesViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - init

- (UILabel *)messageLabel{
    if (!_messageLabel) {
        _messageLabel  = [[UILabel alloc]initWithFrame:CGRectMake(27, 10, 10, 10)];
        _messageLabel.font = DEF_FontSize_8;
        _messageLabel.backgroundColor = getColor(@"ffffff");
        _messageLabel.textColor = getColor(mainColor);
        _messageLabel.layer.masksToBounds = YES;
        _messageLabel.layer.cornerRadius = 5;
        _messageLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _messageLabel;
}

- (UIPageControl *)pageControl{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-100 / WIDTH_5S_SCALE)/2, self.headView.height - 30, 100 / WIDTH_5S_SCALE, 30)];
//        _pageControl.backgroundColor = [UIColor redColor];
//        _pageControl.numberOfPages =  self.rootMallView.dataArray.count / 6 + (self.rootMallView.dataArray.count % 6 == 0 ? 0 : 1);
        _pageControl.currentPage = 0;
        _pageControl.currentPageIndicatorTintColor = getColor(mainColor);
        _pageControl.pageIndicatorTintColor = getColor(@"90cef8");
    }
    return _pageControl;
}

//collectionView
- (RootMallView *)rootMallView{
    if (!_rootMallView) {
        _rootMallView = [[RootMallView alloc]initWithFrame:CGRectMake(0, 150 / WIDTH_5S_SCALE + 63  / WIDTH_5S_SCALE * 2 + 34 / WIDTH_5S_SCALE + 61 / WIDTH_5S_SCALE + 34 / WIDTH_5S_SCALE, SCREEN_WIDTH, 113 / WIDTH_5S_SCALE * 2)];
        __weak __typeof(self)weakSelf = self;
        _rootMallView.getRootMallClick = ^(NSInteger index) {
            NSLog(@"%ld",(long)index);
            MallShopSecondViewController *vc = [MallShopSecondViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            vc.lmId = weakSelf.rootMallView.dataArray[index][@"lm_id"];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        _rootMallView.getCurrentPage = ^(NSInteger page) {
          weakSelf.pageControl.currentPage = page;
        };
    }
    return _rootMallView;
}

- (RootLaundryView *)rootLaundryView{
    if (!_rootLaundryView) {
        _rootLaundryView = [[RootLaundryView alloc]initWithFrame:CGRectMake(0, 150 / WIDTH_5S_SCALE, SCREEN_WIDTH, 63 / WIDTH_5S_SCALE * 2 + 34 / WIDTH_5S_SCALE)];
        __weak __typeof(self)weakSelf = self;
        _rootLaundryView.getRootLaundryClick = ^(NSInteger index) {
            NSLog(@"%ld",index);
            switch (index) {
                case 0:
                {
                    [weakSelf viewCommodityInformation];
                }
                    break;
                case 1:
                {
                    IWantToTakeTheClothesViewController *vc = [IWantToTakeTheClothesViewController new];
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case 2:
                {
                    MemberPrepaidPhoneViewController *vc = [MemberPrepaidPhoneViewController new];
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case 3:
                {
                    ContactCustomerServiceViewController *vc = [ContactCustomerServiceViewController new];
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
                    break;
            }

        };
    }
    return _rootLaundryView;
}

- (SDCycleScrollView *)sdcView{
    if (!_sdcView) {
        _sdcView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150/WIDTH_5S_SCALE)];
        _sdcView.backgroundColor = getColor(mainColor);
        _sdcView.autoScrollTimeInterval = 3.0;
        _sdcView.backgroundColor = getColor(@"bfbfbf");
        _sdcView.pageControlDotSize = CGSizeMake(11, 11);
        _sdcView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        _sdcView.currentPageDotImage = [UIImage imageNamed:@"homepage_banner_point"];
        _sdcView.pageDotImage = [UIImage imageNamed:@"homepage_banner_circle"];
        __block typeof(self) bSelf = self;
        _sdcView.clickItemOperationBlock = ^(NSInteger currentIndex) {
           
        };
        
    }
    return _sdcView;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(50 / WIDTH_5S_SCALE, 0, SCREEN_WIDTH - 30 / WIDTH_5S_SCALE - 50 / WIDTH_5S_SCALE, 46 / WIDTH_5S_SCALE)];
        _titleLabel.font = DEF_FontSize_14;
        _titleLabel.textColor = getColor(mainColor);
        _titleLabel.adjustsFontSizeToFitWidth = YES;
        _titleLabel.numberOfLines = 0;
        //_titleLabel.text = @"您有一个快递包裹至二十一世纪大厦A座1917，取件码【554122】，请您尽快取件！";
        _titleLabel.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(titleLabelCkick)];
        [_titleLabel addGestureRecognizer:tap];
    }
    return _titleLabel;
}


- (UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150 / WIDTH_5S_SCALE + 63 / WIDTH_5S_SCALE * 2 + 34 / WIDTH_5S_SCALE + 61 / WIDTH_5S_SCALE + 113 / WIDTH_5S_SCALE * 2 + 34 / WIDTH_5S_SCALE + 30)];
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15 / WIDTH_5S_SCALE, 150 / WIDTH_5S_SCALE + 63 / WIDTH_5S_SCALE * 2 + 34 / WIDTH_5S_SCALE + 7 / WIDTH_5S_SCALE, SCREEN_WIDTH - 30 / WIDTH_5S_SCALE,   46 / WIDTH_5S_SCALE)];
        bgView.layer.borderColor = getColor(mainColor).CGColor;
        bgView.layer.borderWidth = 1;
        bgView.layer.masksToBounds = YES;
        bgView.layer.cornerRadius = 23 / WIDTH_5S_SCALE;
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5 / WIDTH_5S_SCALE, 0, 36 / WIDTH_5S_SCALE, 46 / WIDTH_5S_SCALE)];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.image = [UIImage imageNamed:@"root_TheHorn"];
        [bgView addSubview:self.titleLabel];
        [bgView addSubview:imageView];
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 63 / WIDTH_5S_SCALE * 2 + 34 / WIDTH_5S_SCALE + 150 / WIDTH_5S_SCALE, SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = getColor(dividerColor);
        
        UIView *line1View = [[UIView alloc]initWithFrame:CGRectMake(0, 63 / WIDTH_5S_SCALE * 2 + 34 / WIDTH_5S_SCALE + 150 / WIDTH_5S_SCALE + 61 / WIDTH_5S_SCALE, SCREEN_WIDTH, 0.5)];
        line1View.backgroundColor = getColor(dividerColor);
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 150 / WIDTH_5S_SCALE + 63  / WIDTH_5S_SCALE * 2 + 34 / WIDTH_5S_SCALE + 61 / WIDTH_5S_SCALE, SCREEN_WIDTH, 34 / WIDTH_5S_SCALE)];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10 / WIDTH_5S_SCALE, 0, SCREEN_WIDTH, 34 / WIDTH_5S_SCALE)];
        titleLabel.font = DEF_FontSize_14;
        titleLabel.textColor = getColor(textColor);
        
        UIView *line2View = [[UIView alloc]initWithFrame:CGRectMake(0, 34 / WIDTH_5S_SCALE, SCREEN_WIDTH, 0.5)];
        line2View.backgroundColor = getColor(dividerColor);
        NSMutableAttributedString *attStr1 = [NSMutableAttributedString new];
        NSTextAttachment *seeAtt1 = [NSTextAttachment new];
        seeAtt1.bounds = CGRectMake(0, -2 / WIDTH_5S_SCALE, 3 / WIDTH_5S_SCALE, 12 / WIDTH_5S_SCALE);
        seeAtt1.image = [UIImage imageNamed:@"root_left"];
        [attStr1 appendAttributedString:[NSAttributedString attributedStringWithAttachment:seeAtt1]];
        [attStr1 appendAttributedString:[[NSAttributedString alloc] initWithString:@"  商城"]];
        titleLabel.attributedText = attStr1;
        [view addSubview:line2View];
        [view addSubview:titleLabel];
        
        [_headView sd_addSubviews:@[self.sdcView , self.rootLaundryView ,lineView , bgView , self.rootMallView ,view , line1View , self.pageControl]];
    }
    return _headView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableFooterView = [UIView new];
        _tableView.tableHeaderView = self.headView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = getColor(@"ffffff");
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self bannerArray];
            [self getMallData];
        }];
    }
    return _tableView;
}

//移除观察者
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
